/*
 * Copyright© 2003-2019 浙江汇信科技有限公司, All Rights Reserved.
 */
package com.icinfo.cloud.provider.punish.csreason.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.icinfo.cloud.common.core.page.PageResponse;
import com.icinfo.cloud.common.security.util.UserUtil;
import com.icinfo.cloud.provider.common.constant.Constant;
import com.icinfo.cloud.provider.punish.csreason.dto.CaseReasonAddParam;
import com.icinfo.cloud.provider.punish.csreason.dto.CaseReasonPageRequest;
import com.icinfo.cloud.provider.punish.csreason.dto.CaseReasonPageResponse;
import com.icinfo.cloud.provider.punish.csreason.dto.CaseReasonTree;
import com.icinfo.cloud.provider.punish.csreason.mapper.CaseReasonManageMapper;
import com.icinfo.cloud.provider.punish.csreason.model.CaseReasonManage;
import com.icinfo.cloud.provider.punish.csreason.service.ICaseReasonContentService;
import com.icinfo.cloud.provider.punish.csreason.service.ICaseReasonManageService;
import com.icinfo.cloud.xzcf.provider.member.userinfo.dto.UserDTO;
import com.icinfo.framework.common.web.Result;
import com.icinfo.framework.core.service.support.MyBatisServiceSupport;
import com.icinfo.framework.mybatis.mapper.entity.Example;
import com.icinfo.framework.mybatis.pagehelper.PageHelper;
import com.icinfo.framework.tools.utils.StringUtils;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 描述:  case_reason_manage 对应的Service接口实现类.<br>
 *
 * @author framework generator
 * @date 2022年10月26日
 */
@Service
public class CaseReasonManageServiceImpl extends MyBatisServiceSupport implements ICaseReasonManageService {
    /**
     * 日志记录器
     */
    private static final Logger logger = LoggerFactory.getLogger(CaseReasonManageServiceImpl.class);

    @Resource
    private CaseReasonManageMapper caseReasonManageMapper;

    @Resource
    private ICaseReasonContentService caseReasonContentService;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<String> save(CaseReasonAddParam param) {
        try {
            UserDTO userInfo = UserUtil.getUserInfo();
            if (ObjectUtil.isEmpty(userInfo)){
                throw new RuntimeException("用户信息获取异常");
            }
            if (StringUtils.isBlank(param.getId())){
                // 新增
                // 保存案由
                CaseReasonManage caseReasonManage = new CaseReasonManage();
                BeanUtil.copyProperties(param,caseReasonManage);
                caseReasonManage.setId(StringUtils.uuid());
                caseReasonManage.setCreateTime(new Date());
                caseReasonManage.setCreateUserId(userInfo.getUserId());
                caseReasonManage.setCreateUser(userInfo.getRealName());
                caseReasonManageMapper.insertSelective(caseReasonManage);
                // 保存案由信息
                this.saveCaseReasonContent(caseReasonManage.getId(),param);
                return Result.success("新增成功");
            } else {
                // 更新案由
                Example example = new Example(CaseReasonManage.class);
                example.createCriteria().andEqualTo("id",param.getId());
                CaseReasonManage caseReasonManage = new CaseReasonManage();
                BeanUtil.copyProperties(param,caseReasonManage);
                caseReasonManage.setUpdateTime(new Date());
                caseReasonManage.setUpdateUserId(userInfo.getUserId());
                caseReasonManage.setUpdateUser(userInfo.getRealName());
                caseReasonManageMapper.updateByExampleSelective(caseReasonManage,example);
                // 删除案由信息
                caseReasonContentService.delete(param.getId(),null);
                // 保存案由信息
                this.saveCaseReasonContent(param.getId(),param);
                return Result.success("编辑成功");
            }
        }catch (Exception e){
            throw new RuntimeException("网络异常，请稍后重试");
        }
    }

    @Override
    public Result<PageResponse<CaseReasonPageResponse>> page(CaseReasonPageRequest request) {
        PageHelper.startPage(request.getPageNum(),request.getLength());
        List<CaseReasonPageResponse> list = caseReasonManageMapper.selectPage(request);
        return Result.success("查询成功",new PageResponse<>(list));
    }

    @Override
    public CaseReasonPageResponse detail(String id) {
        CaseReasonPageRequest caseReasonPageRequest = new CaseReasonPageRequest();
        caseReasonPageRequest.setId(id);
        List<CaseReasonPageResponse> caseReasonPageResponses = caseReasonManageMapper.selectPage(caseReasonPageRequest);
        if (CollectionUtils.isNotEmpty(caseReasonPageResponses) && caseReasonPageResponses.size() > 0){
            CaseReasonPageResponse caseReasonPageResponse = caseReasonPageResponses.get(0);
            List<String> list = caseReasonContentService.selectContentList(id, Constant.STRING_2);
            if (CollectionUtils.isNotEmpty(list)){
                List<List<String>> penaltiesIds = new ArrayList<>();
                for (String twoId : list) {
                    penaltiesIds.add(Arrays.asList(twoId.split(Constant.STRING_COMMA)));
                }
                caseReasonPageResponse.setPenaltiesIds(penaltiesIds);
            }
            return caseReasonPageResponse;
        }
        return new CaseReasonPageResponse();
    }

    @Override
    public List<CaseReasonTree> getCaseReasonTree() {
        List<CaseReasonTree> list = caseReasonManageMapper.selectList();
        List<CaseReasonTree> tree = new ArrayList<>();
        CaseReasonTree caseReasonTree = null;
        for (Map.Entry<String, List<CaseReasonTree>> item : list.stream().collect(Collectors.groupingBy(CaseReasonTree::getTypeName, Collectors.toList())).entrySet()) {
            caseReasonTree = new CaseReasonTree();
            caseReasonTree.setTypeId(item.getValue().get(0).getTypeId());
            caseReasonTree.setTypeName(item.getKey());
            caseReasonTree.setSort(item.getValue().get(0).getSort());
            caseReasonTree.setChildrens(item.getValue());
            tree.add(caseReasonTree);
        }
        tree = tree.stream().sorted(Comparator.comparing(CaseReasonTree::getSort)).collect(Collectors.toList());
        return tree;
    }

    /**
     * 保存违则和处罚事项
     * @param id
     * @param param
     */
    private void saveCaseReasonContent(String id, CaseReasonAddParam param) {
        // 违则
        caseReasonContentService.save(id,param.getViolationList(),Constant.STRING_1);
        // 处罚事项
        List<List<String>> penaltiesList = param.getPenaltiesList();
        if (CollectionUtils.isNotEmpty(penaltiesList)){
            List<String> list = new ArrayList<>();
            for (List<String> twoId : penaltiesList) {
                list.add(String.join(Constant.STRING_COMMA, twoId));
            }
            caseReasonContentService.save(id,list,Constant.STRING_2);
        }
    }
}
